<template>
  <!-- 菜单管理 -->
  <div class="app-container">
    <div class="form-container">
      <el-form ref="filters" :inline="true" label-width="80px" :model="filters">
        <el-form-item label="菜单名称">
          <el-input
            v-model="filters.menuName"
            size="small"
            placeholder="菜单名称搜索"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单状态" prop="visible">
          <el-select
            v-model="filters.visible"
            size="small"
            clearable
            placeholder="请选择"
            prop="visible"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select
            v-model="filters.menuType"
            size="small"
            clearable
            placeholder="请选择"
            prop="menuType"
          >
            <el-option
              v-for="dict in menuTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            size="small"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:225px"
            clearable
          />
        </el-form-item>
        <!--
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item> -->
        <!-- 高级设置一栏 start -->
        <!-- <el-form-item>
          <slot name="label"> -->
        <!-- <span class="highLevelStyle" @click="highLevelSet = !highLevelSet">高级设置</span> -->
        <!-- <i class="highLevelStyle" :class="highLevelSet===true?'el-icon-arrow-up':'el-icon-arrow-down'" @click="highLevelSet = !highLevelSet" />
          </slot>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="btns-group">
      <systemBtns :single="isAmend" has-permi="menu" />
      <el-button v-show="isStatusShow === '1'" v-hasPermi="[`system:menu:edit`]" size="middle" :disabled="isAmend" icon="el-icon-star-on" @click="handleStatusChange">
        启用
      </el-button>
      <el-button v-show="isStatusShow === '0'" v-hasPermi="[`system:menu:edit`]" size="middle" :disabled="isAmend" icon="el-icon-star-off" @click="handleStatusChange">
        停用
      </el-button>
    </div>
    <!-- 树形表格展示start -->
    <div ref="table">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="treeData"
        :row-style="rowClass"
        stripe
        class="table-list"
        :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height-tree' : 'el-body-page-roll-height-tree') :
          (needTagsView===true ? 'el-body-page-roll-tag-tree' : 'el-body-page-roll-tree')"
        row-key="menuId"
        :default-expand-all="false"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @selection-change="handleSelectionChange"
        @row-click="rowChecked"
      >
        <el-table-column type="selection" width="38" />
        <el-table-column prop="menuName" header-align="center" label="菜单名称" width="200px" :show-overflow-tooltip="true" />
        <el-table-column prop="menuType" align="center" label="菜单类型" width="80px">
          <template slot-scope="scope" :formatter="statusFormat">
            <span v-if="scope.row.menuType=== 'M'">目录</span>
            <span v-if="scope.row.menuType=== 'C'">菜单</span>
            <span v-if="scope.row.menuType=== 'F'">按钮</span>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" align="center" min-width="40">
          <template slot-scope="scope">
            <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" />
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" align="center" label="排序" min-width="40px" />
        <el-table-column prop="perms" align="center" label="权限标识" min-width="230" />
        <el-table-column prop="url" align="center" label="组件路径" min-width="160" />
        <el-table-column prop="dataObjType" align="center" label="实体名称" min-width="150px" />
        <el-table-column prop="visible" align="center" label="状态" min-width="40px">
          <template slot-scope="scope" :formatter="statusFormat">
            <span v-if="scope.row.visible=== '0'">正常</span>
            <span v-if="scope.row.visible=== '1'">停用</span>
          </template>
        </el-table-column>
        <!-- W -->
      </el-table>
    </div>
    <!-- 树形表格展示end-->
    <!-- 添加页面 start-->
    <addDialog ref="addDialog" :menu-type-options="menuTypeOptions" />
    <!-- 添加页面 end -->
  </div>
</template>

<script>
import { listMenu, updateMenu, delMenu } from '@/api/system-tool/menu'
import { mapState } from 'vuex'
// 按钮组件
import systemBtns from '@/components/Common/Btns/systemBtns'
import addDialog from './components/addDialog'
export default {
  components: { systemBtns, addDialog },
  data() {
    return {
      isStatusShow: '0',
      // 高级设置显示隐藏
      highLevelSet: false,
      // 高级设置参数
      highLevelSettingData: [
        {
          label: '创建时间',
          isDatePicker: 1,
          size: 'small',
          type: 'daterange',
          separator: '-',
          start: '开始日期',
          end: '结束日期',
          isClearable: false,
          prop: 'createTime',
          model: []
        }
      ],
      // 修改按钮是否可用
      isAmend: true,
      // 删除按钮是否可用
      isDelete: true,
      // 搜索字段
      filters: {
        menuName: '',
        visible: '0',
        menuType: '',
        createTime: ''
      },
      // 时间范围数组
      dateRange: [],
      // 高亮数组
      selectRow: [],
      rowTableData: [],
      statusOptions: [],
      menuTypeOptions: [],
      treeData: [],
      total: 0,
      // 选中行的id
      multipleSelection: [],
      // 表格加载是否显示等待图标
      loading: false

    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    })
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data.rows
    })
    this.getDicts('sys_menu_menuType').then(response => {
      this.menuTypeOptions = [...this.menuTypeOptions, ...response.data.rows]
    })
  },
  mounted() {
    window.onresize = () => {
      // 调用methods中的事件
      // this.AddTaleData(this.treeData, this.total)
    }
    // 跳转路由时关闭窗口提交
    this.$once('hook:beforeDestroy', () => {
      window.onresize = null
    })
  },
  methods: {
    // 获取高级设置中子组件传递的数据
    getValueFromChild(data) {
      this.highLevelQueryParams = data
    },
    // 菜单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.visible)
    },
    // 菜单类型字典翻译
    menuTypeFormat(row, column) {
      return this.selectDictLabel(this.menuTypeOptions, row.menuType)
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },

    // 选择每行表格前的复选框
    handleSelectionChange(selection) {
      if (selection[0] !== undefined) {
        if (JSON.stringify(selection[0]) === '{}') {
          selection = []
          this.$refs.multipleTable.clearSelection()
        }
      }
      this.multipleSelection = selection
      this.isAmend = selection.length !== 1
      this.isDelete = selection.length !== 1
      this.multipleSelection = selection
      if (selection.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(selection.pop())
      }
      if (this.multipleSelection.length === 1) {
        this.isStatusShow = this.multipleSelection[0].visible
      }
      this.selectRow = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.rowTableData.indexOf(item))
        })
      }
    },
    // 加载树形表格
    getList() {
      this.loading = true
      listMenu(this.changeDateRange(this.filters, this.dateRange)).then(resp => {
        // this.treeData = resp.data
        if (resp) {
          this.treeData = resp.data || []
          this.rowTableData = []
          this.getTableData(this.treeData)
          // 空白行添加
          this.total = resp.data.length || 0
          // this.AddTaleData(resp.data, this.total)
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 空白行添加
    AddTaleData(arr, num) {
      const tableHeight = this.$refs.table.offsetHeight
      const row = Math.floor(
        (tableHeight - 36) / 36 // 表格：表头/行高：36px
      )
      for (let i = 0; i < (row - num); i++) {
        this.treeData.push({})
      }
    },
    // 选择表格前面的对话框时触发的方法
    getTableData(obj) {
      for (const i in obj) {
        this.rowTableData.push(obj[i])
        if (obj[i].children) {
          this.getTableData(obj[i].children)
        }
      }
    },
    // 搜索方法
    handleQuery() {
      this.getList()
    },
    // 重置
    resetQuery() {
      this.resetForm('filters')
      this.filters = {}
      this.dateRange = []
      this.getList()
    },

    // 点击添加菜单弹出的对话框
    handleAdd() {
      let parentId = null
      if (this.multipleSelection.length !== 0) {
        parentId = this.multipleSelection[0].menuId
      }
      this.$refs.addDialog.handleAdd('新增菜单', undefined, parentId)
    },
    // 编辑操作
    handleUpdate() {
      const menuId = this.multipleSelection[0].menuId
      this.$refs.addDialog.handleAdd('修改菜单', menuId)
    },
    // 删除操作
    handleDelete() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const ids = this.multipleSelection.map(item => item.menuId).join(',')
          console.log(ids)
          delMenu(ids).then(resp => {
            if (resp) {
              this.msgSuccess('删除成功!')
              // 重新加载表格数据
              this.getList()
            }
          })
        })
        .catch(() => {
        })
    },
    // 用户状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.visible === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + row.menuName + '用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          row.visible = row.visible === '0' ? '1' : '0'
          const { menuId, parentId, menuType, icon, menuName,
            orderNum, url, component, perms, visible } = row
          // this.sysmenu = {
          //   ...this.sysmenu, menuId, parentId, menuType, icon, menuName,
          //   orderNum, url, component, perms, visible }
          updateMenu({ menuId, parentId, menuType, icon, menuName,
            orderNum, url, component, perms, visible }).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
            }
          })
        })
        .catch(() => {
        })
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    }
  }
}
</script>

<style scoped>
</style>
